package main

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
)

// 查询参数 http://localhost:8080/query?name=zhangsna&name=lisi
func _query(c *gin.Context) {
	fmt.Println(c.Query("name"))
	name, ok := c.GetQuery("name")
	if ok {
		fmt.Println(name)
	} else {
		fmt.Println("not found")
	}
	fmt.Println(c.QueryArray("name"))
}

// 动态参数 http://localhost:8080/param/1
func _param(c *gin.Context) {
	fmt.Println(c.Param("id"))
}

// 表单参数 http://localhost:8080/form
func _form(c *gin.Context) {
	fmt.Println(c.PostForm("name"))
	fmt.Println(c.PostFormArray("name"))
	fmt.Println(c.DefaultPostForm("addr", "addr"))
}

// 原始参数
func _ram(c *gin.Context) {
	data, err := c.GetRawData()
	fmt.Println(string(data), err)
}
func _json(c *gin.Context) {
	data, _ := c.GetRawData()
	contentType := c.GetHeader("Content-Type")
	switch contentType {
	case "application/json":

		type User struct {
			Name string `json:"name"`
			Age  int    `json:"age"`
		}
		var user User
		err := json.Unmarshal(data, &user)
		if err != nil {
			fmt.Println(err.Error())

		}
		fmt.Println(user)
	}
}
func main() {
	r := gin.Default()
	r.LoadHTMLGlob("templates/*")
	r.StaticFile("/static/demo01.png", "./static/demo01.png")
	r.GET("/query", _query)
	r.GET("/param/:id", _param)
	r.POST("/form", _form)
	r.POST("/ram", _ram)
	r.POST("/json", _json)
	err := r.Run(":8080")
	if err != nil {
		return
	}
}
